define([],
function() {
    function initStrut(defTpl) {

};

    function loadScript(res, defTpl) {
        // 处理脚本加载
        var jsRegex = /.*(\.js)$/;
        var jspRegex = /.*(\.jsp)$/;
        if (res.scriptPath) {
            if (res.scriptPath.match(jsRegex)) {
                $.ajax({
                    async: false,
                    cache: false,
                    dataType: "script",
                    type: "GET",
                    url: root + res.scriptPath
                });
            } else if (res.scriptPath.match(jspRegex)) {
                $.ajax({
                    async: false,
                    cache: false,
                    dataType: "html",
                    success: function(data) {
                        defTpl._$script.html(data);
                    },
                    type: "GET",
                    url: root + res.scriptPath
                });
            }
        }
    };

    function parserSearchColCtr(col) {
        var cols = [];
        if (col.controlType == 1) {
            var c = {
                ctr: '<div class="form-group">' + '<label>' + col.viewName + '</label>' + '<input type="text" class="form-control" name="' + getColName(col) + '" >' + '</div>'
            }
            cols.push(c);
        } else if (col.controlType == 2) {
            var c = {
                ctr: $('<div class="form-group" style="position: relative;">' + '<label>' + col.viewName + '</label>' + '<input type="text" class="form-control" name="' + getColName(col) + '" data-am-datepicker>' + '</div>'),
                onAfterAppend: function() {
                    var div = this.ctr;
                    div.find("input").datetimepicker({
                        format: 'YYYY-MM-DD',
                        locale: "zh-cn"
                    });
                }
            }
            cols.push(c);

            if (col.conditionType == 11) {
                c = {
                    ctr: $('<div class="form-group" style="position: relative;">' + '<label>至</label>' + '<input type="text" class="form-control" name="' + getColName(col) + '_E">' + '</div>'),
                    onAfterAppend: function() {
                        var div = this.ctr;
                        div.find("input").datetimepicker({
                            format: 'YYYY-MM-DD',
                            locale: "zh-cn"
                        });
                    }
                }
                cols.push(c);
            }

        } else if (col.controlType == 3) {
            var c = {
                ctr: $('<div class="form-group" style="position: relative;">' + '<label>' + col.viewName + '</label>' + '<input type="text" class="form-control" name="' + getColName(col) + '">' + '</div>'),
                onAfterAppend: function() {
                    var div = this.ctr;
                    div.find("input").datetimepicker({
                        format: 'YYYY-MM-DD HH:mm',
                        locale: "zh-cn"
                    });
                }
            }
            cols.push(c);

            if (col.conditionType == 11) {
                var c = {
                    ctr: $('<div class="form-group" style="position: relative;">' + '<label>至</label>' + '<input type="text" class="form-control" name="' + getColName(col) + '_e" data-am-datepicker >' + '</div>'),
                    onAfterAppend: function() {
                        var div = this.ctr;
                        div.find("input").datetimepicker({
                            format: 'YYYY-MM-DD HH:mm',
                            locale: "zh-cn"
                        });
                    }
                }
                cols.push(c);
            }
        } else if (col.controlType == 4) {
            var html = '<div class="form-group">' + '<label>' + col.viewName + '</label>' + '<select  class="form-control" name="' + getColName(col) + '" >';
            html += '<option value=""></option>';
            var items = webUtils.getDataDicItems(col.controlScript);
            $.each(items,
            function(i, n) {
                html += '<option value="' + n.value + '">' + n.name + '</option>';
            });

            html = html + '</select>' + '</div>';
            var c = {
                ctr: $(html),
                onAfterAppend: function() {
                    var div = this.ctr;
                    div.find("input").datetimepicker({
                        format: 'YYYY-MM-DD HH:mm',
                        locale: "zh-cn"
                    });
                }
            }
            cols.push(c);
        }

        return cols

        function getColName(col) {
            return col.name;
        }
    }

    function renderToColumn(n) {
        var column = {};
        column = {
            title: n.viewName,
            field: n.name.toUpperCase(),
            width: n.width == 'auto' ? null: n.width,
            sortable: n.sortAble == 1
        };
        if (n.renderType) {
            if (n.renderType == 1) {
                column.formatter = function(data, row, index) {
                    return data ? webUtils.parseTimestamp(data, n.renderScript) : "";
                }
            } else if (n.renderType == 2) {
                column.formatter = function(data, row, index) {
                    var t = eval("(function _t(grid,data, row, index){" + n.renderScript + "})");
                    var v = t.call(null, this, data, row, index);
                    return v;
                }
            } else if (n.renderType == 3) {
                column.formatter = function(data, row, index) {
                    var v = "";
                    if (data != undefined) {
                        var dicItem = webUtils.getDataDicItemVal(n.renderScript, data);
                        if (dicItem) {
                            v = dicItem.name;
                        }
                    }
                    return v;
                }
            }
        }
        return column;
    }

    var queryDefTpl = function(params) {
        var uuid = webUtils.uuid;
        var me = this;
        this.params = $.extend({
            code: "",
            // 查询定义的编码
            scriptDiv: "",
            // 引用脚本的div
            searchDiv: "",
            // 查询定义栏
            toolBarDiv: "",
            // 工具栏
            gridDiv: "",
            pageSize:30,
            // grid表格
            gridCfg: {},
            // grid的配置信息，可以覆盖原配置
            model: 'serverEdit',
            // 'select'选择模型,'servierMix'混合模式,'serverEdit'服务编辑模式,'clientEdit'客户端编辑模式
            selectModel: 'multi',
            // single单选,multi多选
            exportDataType: 'all',
            showExport: false,
            winId: "",
            queryDatas: {},
            onSelect: function(row) {

            },
            onBeforeLoad: function(gridDef, grid) {
                return true;
            }
        },
        params);
        this.url = ctx + "/queryDefAction/queryDatas.do?code=" + this.params.code;
        this._$script = this.params.scriptDiv ? $(this.params.scriptDiv) : null;
        this._$search = this.params.searchDiv ? $(this.params.searchDiv) : null;
        this._$grid = this.params.gridDiv ? $(this.params.gridDiv) : null;

        $.ajax({
            async: false,
            data: {
                code: this.params.code,
                withStruts: true
            },
            dataType: "json",
            type: "GET",
            url: ctx + "/queryDefAction/findQueryDefByCode.do",
            success: function(res) {
                // --------------------------加载脚本
                loadScript(res, me);
                // --------------------------加载按钮
                var defalutOptBtns = [];
                var inGridOptBtns = [];
                if (res.optBtns) {
                    $.each(res.optBtns,
                    function(i, n) {
                        if (webUtils.hasAllPermissions(n.optAuthCode)) {
                            if (n.btnType == "IN_GRID_ROW") {
                                inGridOptBtns.push(n);
                            } else {
                                defalutOptBtns.push(n);
                            }

                        }
                    });
                }
                
                if (res.searchColumns && me._$search) { //处理搜索工具条
                    $.each(res.searchColumns,
                    function(i, n) {
                        if (n.canView == 1) {
                            var controls = parserSearchColCtr(n);
                            $.each(controls,
                            function(ctr_i, ctr_n) {
                                me._$search.append(ctr_n.ctr);
                                if (ctr_n.onAfterAppend) {
                                    ctr_n.onAfterAppend.call(ctr_n);
                                }
                            });
                        }
                    });
                    
                    
                    var searhchBt = $('<button type="button" class="am-margin-left-xs btn btn-sm btn-primary">搜索</button>');
                    var searchDialog;
                    searhchBt.click(function() {
                    	var datas=webUtils.formToObj(me._$search);
                    	me.search(datas);
                    	if(searchDialog){
                    		searchDialog.close();
                    	}
                    });
                    me._$search.append($('<div class="searchBtBar"></div>').append(searhchBt));
                    me._$search.append('<div style="clear:both"></div>');
                    //TODO
                    
                   
                }
                //-------------处理工具条
                var toolbar = $(me.params.toolBarDiv);
                
                if (toolbar.size() > 0 &&  me.params.searchBarType=='dialog') {
                	var btn = $('<a class="btn btn-sm btn-default am-margin-left-xs">' + '<span class="glyphicon glyphicon-search"></span> 搜索' + '</a>');
                    
                	btn.click(function() {
                    	searchDialog=webUtils.dialog({
                    		type: 1,
                    		dom:$(me.params.searchDiv)
                    	});
                    });
                    
                    toolbar.prepend(btn);
                }
                
                if (toolbar.size() > 0) {

                    if (defalutOptBtns && $.inArray(me.params.model, ['serverEdit', 'clientEdit', 'servierMix']) > -1) { // 处理按钮
                        $.each(defalutOptBtns,
                        function(i, n) {
                            var btn = $('<a class="btn btn-sm ' + (n.btnCls ? n.btnCls: "btn-default") + ' am-margin-left-xs" title="' + n.title + '">' + (n.iconCls ? '<span class="' + n.iconCls + '"></span> ': '') + (!n.notDisplayTitle ? n.title: "") + '</a>');
                            btn.click(function() {
                                if (n.exeScript) {
                                    var t = eval("(function _t(grid,optBtnData,gridDef){" + n.exeScript + "(grid,optBtnData,gridDef);})");
                                    var v = t.call(null, me.grid, n, me);
                                }
                            });
                            toolbar.append(btn);
                        });
                    }
                    if ($.inArray(me.params.model, ['select', 'servierMix']) > -1) {
                        var btn = $('<a class="btn btn-sm btn-primary am-margin-left-xs">' + '<span class="glyphicon glyphicon-ok aria-hidden="true"></span> 选择' + '</a>');
                        btn.click(function() {
                            var rows = me.grid.rows({
                                selected: true
                            }).data();
                            if (rows && rows.length > 0) {
                                if (me.params.winId) {
                                    webUtils.topicPublish("queryData.selected." + me.params.winId, rows);
                                }
                            } else {
                                webUtils.alert("请勾选需要的数据");
                            }
                        });
                        toolbar.append(btn);
                    }
                }
                // --------------------------加载列
                var _columns = [];
                if(me.params.selectModel!='single'){
                	_columns.push({
                        checkbox: true
                    });
                }
                var sortName;
                var sortOrder = 'asc';
                if (res.viewColumns) { // 处理Grid列字段
                    // _columns.push({field: '_temp_id',
                    // checkbox: true});
                    $.each(res.viewColumns,
                    function(i, n) {
                        if (n.canView == 1) {
                            n.name = n.name.toUpperCase();
                            _columns.push(renderToColumn(n));

                            if (n.sortAble == 1 && n.isDefaultSort == 1) {
                                sortName = n.name;
                                sortOrder = n.defaultSortAsc
                            }

                        }
                    });

                    if (inGridOptBtns && inGridOptBtns.length && $.inArray(me.params.model, ['serverEdit', 'clientEdit', 'servierMix']) > -1) {
                        _columns.push({
                            title: "操作",
                            formatter: function(data, row, index) {
                                var html = [];
                                $.each(inGridOptBtns,
                                function(bti, btn) {
                                    html.push('<button data-rowindex="' + index + '" data-exe="' + btn.exeScript + '" type="button" title="' + btn.title + '" class="btn ' + (btn.btnCls ? btn.btnCls: "btn-default") + ' btn-xs am-margin-left-xs am-margin-vertical-xs inGridOptBtn">' + (btn.iconCls ? '<span class="' + btn.iconCls + '"></span> ': '') + (!btn.notDisplayTitle ? btn.title: "") + '</button>');
                                });
                                return html.join("");
                            }
                        })
                    }
                }

                // --------------------------处理Grid结构
                me.params.gridCfg = $.extend({
                    sidePagination: me.params.model == "clientEdit" ? 'client': 'server',
                    pagination: !(me.params.model == "clientEdit"),
                    url: me.url,
                    sortName: sortName,
                    sortOrder: sortOrder,
                    pageSize:me.params.pageSize,
                    queryParams: function(d) {
                        var searchData = {}
                        if (me._$search) {
                            searchData = webUtils.formToObj(me._$search);
                        }
                        $.extend(searchData, me.params.queryDatas);
                        searchData = JSON.stringify(searchData);
                        d.searchData = searchData;
                        return d;
                    },
                    ajaxOptions: {
                        beforeSend: function(xhr) {
                            if (me.params.onBeforeLoad.call(this, me, me.grid)) {
                                return this;
                            } else {
                                return false;
                            }
                        }
                    },
                    columns: _columns,
                    singleSelect: me.params.selectModel == 'single' ? true: false,
                    onLoadSuccess: function() {
                        me._$grid.find(".inGridOptBtn").click(function() {
                            var that = $(this);
                            var rowindex = that.data("rowindex");
                            var exeScript = that.data("exe");
                            var t = eval("(function _t(grid,rowindex,gridDef){" + exeScript + "(grid,rowindex,gridDef);})");
                            t.call(null, me.grid, rowindex, me);
                        });
                        if (params.onLoadSuccess) {
                            me.params.onLoadSuccess.call(null, me, me.grid);
                        }
                    },
                    onClickRow: function(row, $tr) {
                        me.params.onSelect.call(this, row, $tr.index());
                    }
                },
                me.params.gridCfg);

                me.grid = me._$grid.bootstrapTable(me.params.gridCfg);

                
            }
        });

        this.getGrid = function() {
            return me.grid;
        }
        this.getData = function(useCurrentPage) {
            return me.grid.bootstrapTable('getData', useCurrentPage);
        }
        this.search = function(datas) {
            $.extend(me.params.queryDatas, datas);
            me.grid.bootstrapTable('refresh');
        }
        this.loadOnServer = function(datas) {
            $.extend(me.params.queryDatas, datas);
            me.grid.bootstrapTable('refreshOptions', {
                sidePagination: 'server',
                pagination: true
            });
        }
    }

    return queryDefTpl;
});